package cuiyt.datastructure.queue.criclequeue.decirclequeue;

/**
 * @author cyt
 * @create 2020-12-05 17:57
 */
public class DeCriCleQueue<E> {
    /**
     * 双端循环循环队列
     */
    private int size;
    private E[] elements = (E[]) new Object[10];
    private int front;

    public E deDeQueueFront() {
        E element = elements[front];
        elements[front] = null;
        front = getIndex(1);
        size--;
        return element;
    }

    public E deDeQueueRear() {
        E element = elements[getIndex(size - 1)];
        elements[getIndex(size - 1)] = null;
        size--;
        return element;
    }

    public void enDeQueueFront(E element) {
        ensureCapacity(size + 1);
        front = getIndex(-1);
        elements[front] = element;
        size++;
    }

    public void enDeQueueRear(E element) {
        ensureCapacity(size + 1);
        elements[getIndex(size)] = element;
        size++;
    }

    public int size() {
        return size;
    }

    public E rear() {
        return elements[getIndex(size - 1)];
    }

    public E front() {
        return elements[front];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    private int getIndex(int bias) {
        bias = front + bias;
        if (bias < 0) {
            return bias + elements.length;
        }
        return bias % elements.length;
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) {
            return;
        }
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[getIndex(i)];
        }
        elements = newElements;
        front = 0;
        System.out.println(oldCapacity + " =  > > " + newCapacity);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Capacity = " + elements.length)
                .append(", Size = " + size)
                .append(",  front = " + front)
                .append(" [ ");
        for (int i = 0; i < elements.length; i++) {
            sb.append(elements[i]);
            if (i != elements.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
